var tools = {};

tools.parseUrl = function(url) {
  var r = {
    protocol: /([^\/]+:)\/\/(.*)/i,
    host: /(^[^\:\/]+)((?:\/|:|$)?.*)/,
    port: /\:?([^\/]*)(\/?.*)/,
    pathname: /([^\?#]+)(\??[^#]*)(#?.*)/
  };
  var tmp, res = {};
  res["href"] = url;
  for (var p in r) {
    tmp = r[p].exec(url);
    res[p] = tmp[1];
    url = tmp[2];
    if (url === "") {
      url = "/";

    }
    if (p === "pathname") {
      res["pathname"] = tmp[1];
      res["search"] = tmp[2];
      res["hash"] = tmp[3];

    }
  }
  return res;
};
tools.url_to_host = function(url) {
  var ret = tools.parseUrl(url);
  var pathName = ret.pathname;
  var projectname = pathName.substring(1, pathName.substr(1).indexOf('/') + 1);
  if (projectname !== 'app') {
    return ret.protocol + '//' + ret.host + '/' + projectname;
  } else {
    return ret.protocol + '//' + ret.host;
  }

};
tools.isnull = function(str) {
  if ((!str) || (typeof(str) == "undefined") || (str == null) || (str == 0) || str=='') {
    return true;
  } else {
    return false;
  }
};
/**
 * 收藏房源
 */
tools.add_favorite = function($this, params) {
  var app = getApp();
  app.checkAuthorLogin($this);
  app.util.request({
    'url': 'entry/wxapp/addfavorite',
    data: params,
    success(res) {
      /**处理数据 */
      wx.showToast({
        title: res.data.message,
      })
    }
  })

};

/**获取系统参数设置，缓存有就读取缓存，没有就加载url */
tools.get_settingdata = function(self, callback) {
  var app = getApp();
  /*wx.getStorage({
    key: 'shop',
    success: function(res) {
        callback(res)
    },
    fail: function(){*/
  /**获取参数SettingData */
  app.util.request({
    'url': 'entry/wxapp/settingData',
    'cachetime': '60',
    showLoading: false,
    data: {
      'fkey[0]': 'logo',
      'fkey[1]': 'banner',
      'fkey[2]': 'shopname',
      'fkey[3]': 'copyinfo',
      'fkey[4]': 'cityprice',
      'fkey[5]': 'saletotal',
    },
    success(res) {
      /*存缓存*/
      wx.setStorage({
        'key': 'shop',
        'data': res.data.data,
        'success': function() {}
      });
      /*返回数据*/
      callback(res.data);
    }
  });
  /*}
  })*/

};
/**微信支付助手 */
/**发起微信支付功能 
 * self = 上下文, actname 付款类型 ,callback 付款成功回调函数
 */
tools.wxpayHelper = function(self, actname, callback) {
  var app = getApp();
  var money = self.data.money;
  if (!money) {
    wx.showToast({
      title: '请输入金额',
      icon: 'none',
      duration: 1000
    });
    return false;
  }
  app.util.request({
    'url': 'entry/wxapp/pay', //调用wxapp.php中的doPagePay方法获取支付参数
    data: {
      money: money,
      actname: actname
    },
    'cachetime': '0',
    success(res) {
      if (res.data && res.data.data && !res.data.errno) {
        //发起支付
        wx.requestPayment({
          'timeStamp': res.data.data.timeStamp,
          'nonceStr': res.data.data.nonceStr,
          'package': res.data.data.package,
          'signType': 'MD5',
          'paySign': res.data.data.paySign,
          'success': function(res) {
            //执行支付成功提示
            callback();
          },
          'fail': function(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'none',
              duration: 1000
            });
          }
        })
      }
    },
    fail(res) {
      wx.showModal({
        title: '系统提示',
        content: res.data.message ? res.data.message : '错误',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            wx.showToast({
              title: '支付失败',
              icon: 'none',
              duration: 1000
            });
          }
        }
      })
    }
  })
};
/**合并两个变量 */
tools.extend = function(des, src, override) {
  if (src instanceof Array) {
    for (var i = 0, len = src.length; i < len; i++)
      tools.extend(des, src[i], override);
  }
  for (var i in src) {
    if (override || !(i in des)) {
      des[i] = src[i];
    }
  }
  return des;
};
/**获取站点广告数据 */
tools.siteAdvancise = function(app, self) {
  app.util.request({
    'url': 'entry/wxapp/enset',
    'cachetime': '30',
    showLoading: false,
    data: {
      'op': 'adinfo'
    },
    success(res) {
      self.setData({
        adinfo: res.data.data
      })
    }
  });
  /**发送formsid */
  let formIds = app.globalData.formids; 
  //获取全局数据中的推送码gloabalFomIds数组
  if (!formIds) formIds = [];
  if (formIds.length) {//gloabalFomIds存在的情况下 将数组转换为JSON字符串
    formIds = JSON.stringify(formIds);
    app.globalData.formids = [];
    app.util.request({
      'url': 'entry/wxapp/enset', 
      method: 'POST',     
      data: {
        'op': 'saveformsid',
        formid: formIds
      },
      success(res) { }
    });
  }  
   
};
 /**全局保存formid 保存的 formid 通过 siteAdvancise 发送到服务器端保存 */
tools.dealFormIds = function ( formId) {
  var app = getApp();
  let formIds = app.globalData.formids;//获取全局数据中的推送码gloabalFomIds数组
  if (!formIds) formIds = [];
  let data = {
    formId: formId,
    expire: parseInt(new Date().getTime() / 1000) + 604800 //计算7天后的过期时间时间戳
  }
  formIds.push(data);//将data添加到数组的末尾
  app.globalData.formids = formIds; //保存推送码并赋值给全局变量
  console.log(app.globalData.formids)
}; 
/**全局响应绑定时间处理 导航问题 */
tools.defRedirect = function (app, e) {
  try {
    var formId = e.detail.formId;
    var type = e.detail.target.dataset.type;
    var data = e.detail.target.dataset;
    this.dealFormIds(  formId); //处理保存推送码
    if (type == 'navtab') {
      if (this.isnull(app.data.showRightMenuOk)) {
        app.setData({
          showRightMenuOk: true
        })
      } else {
        app.setData({
          showRightMenuOk: false
        })
      }
    } else if (type == 'switchTab'){
        wx.switchTab({
          url: data.url,
        })
    } else {      
      if (this.isnull(data.appid)) {
        if (!this.isnull(data.url)) {
          wx.navigateTo({
            url: data.url,
          })
        } else {
          console.log(e);
        }
      } else {
        wx.navigateToMiniProgram({
          appId: data.appid,
          path: data.url
        })
      }
    }
  } catch (error) {
    this.defRedirect_old(app,e);
  }
}
/**全局响应绑定时间处理 导航问题 */
tools.defRedirect_old = function(app, e) {
  try {
    var type = e.currentTarget.dataset.type;
    if (type == 'navtab') {
      if (this.isnull(app.data.showRightMenuOk)) {
        app.setData({
          showRightMenuOk: true
        })
      } else {
        app.setData({
          showRightMenuOk: false
        })
      }
    } else {
      var data = e.currentTarget.dataset;
      if (this.isnull(data.appid)) {
        if (!this.isnull(data.url)) {
          wx.navigateTo({
            url: data.url,
          })
        } else {
          console.log(e);
        }
      } else {
        wx.navigateToMiniProgram({
          appId: data.appid,
          path: data.url
        })
      }
    }
  } catch (e) {
    console.log(e);
  }
}
/**这个是生成海报的方法 */
tools.sharePaperDrawing = function(that, info) {

  var context = wx.createCanvasContext('mycanvas');
  context.setFillStyle("#FFFFFF")
  context.fillRect(0, 0, 375, 667)

  //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
  wx.getImageInfo({
    src: info.thumb,
    success: function(e) {
      console.log(e);
      context.drawImage(e.path, 0, 0, 375, 183);

      //不知道是什么原因，手机环境能正常显示

      var path1 = "/wdl_weihouse/static/images/get_avatar.png";

      //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
      var path2 = "/wdl_weihouse/static/images/get_avatar.png";
      var path3 = "/wdl_weihouse/static/images/get_avatar.png";
      var path4 = "/wdl_weihouse/static/images/get_avatar.png";
      var path5 = "/wdl_weihouse/static/images/get_avatar.png";
      context.drawImage(path2, 126, 186, 120, 120);
      //不知道是什么原因，手机环境能正常显示
      // context.save(); // 保存当前context的状态

      var name = '我是分享达人';
      //绘制名字
      context.setFontSize(24);
      context.setFillStyle('red');
      context.setTextAlign('center');
      context.fillText(name, 185, 340);
      context.stroke();
      //绘制一起吃面标语
      context.setFontSize(14);
      context.setFillStyle('red');
      context.setTextAlign('center');
      context.fillText("邀请你一起去吃面", 185, 370);
      context.stroke();
      //绘制验证码背景
      context.drawImage(path3, 48, 390, 280, 84);
      //绘制code码
      context.setFontSize(40);
      context.setFillStyle('#ffe200');
      context.setTextAlign('center');
      context.fillText('5622211', 185, 435);
      context.stroke();
      //绘制左下角文字背景图
      context.drawImage(path4, 25, 520, 184, 82);
      context.setFontSize(12);
      context.setFillStyle('red');
      context.setTextAlign('left');
      context.fillText("进入小程序输入朋友的邀请", 35, 540);
      context.stroke();
      context.setFontSize(12);
      context.setFillStyle('red');
      context.setTextAlign('left');
      context.fillText("码，朋友和你各自获得通用", 35, 560);
      context.stroke();
      context.setFontSize(12);
      context.setFillStyle('red');
      context.setTextAlign('left');
      context.fillText("优惠券1张哦~", 35, 580);
      context.stroke();
      //绘制右下角扫码提示语
      context.drawImage(path5, 248, 578, 90, 25);
      //绘制头像
      context.arc(186, 246, 50, 0, 2 * Math.PI) //画出圆
      context.strokeStyle = "#ffe200";
      context.clip(); //裁剪上面的圆形
      context.drawImage(path1, 136, 196, 100, 100); // 在刚刚裁剪的园上画图
      context.draw();
      //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
      setTimeout(function() {
        wx.canvasToTempFilePath({
          canvasId: 'mycanvas',
          success: function(res) {
            var tempFilePath = res.tempFilePath;
            that.setData({
              imagePath: tempFilePath,
              canvasHidden: true
            });
          },
          fail: function(res) {
            console.log(res);
          }
        });
      }, 200);

    }
  })
}


module.exports = tools;